<template>
    <div v-loading="loading" class="page flex flex-column">
        <!-- 搜索栏 -->
        <div class="toppage">
            <el-form size="small" :inline="true" :model="serachForm" class="demo-form-inline">
                <el-form-item class='ml10' label="用户名称">
                    <el-input v-model="serachForm.name" placeholder="模糊匹配"></el-input>
                </el-form-item>
                <el-form-item class='ml10' label="用户编号">
                    <el-input v-model="serachForm.code" placeholder="用户编号"></el-input>
                </el-form-item>
                <el-form-item class='ml10' label="职位">
                    <el-select v-model="serachForm.identityid">
                        <el-option :value="1" label="管理员"></el-option>
                        <el-option :value="2" label="操作员"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item class='ml10'>
                    <el-button :disabled="!permissionInfo.select" type="primary" @click="onSerach">查 询</el-button>
                    <el-button @click="onEmpty">重 置</el-button>
                </el-form-item>
            </el-form>
        </div>

        <!-- 显示栏 -->
        <div class="bottompage flex flex-column">

            <div class="bottompage-table">
                <el-table @selection-change="tableSelectionChange" :stripe="true" height="100%" :data="tableData"
                    style="width: 100%" :default-sort="{ prop: 'date', order: 'descending' }">
                    <el-table-column type="selection" width="55">
                    </el-table-column>
                    <el-table-column prop="opertime" label="日期" sortable width="180">
                    </el-table-column>
                    <el-table-column prop="name" label="名称" width="180">
                    </el-table-column>
                    <el-table-column prop="code" label="编号">
                    </el-table-column>
                    <el-table-column prop="phone" label="手机号">
                    </el-table-column>
                    <el-table-column prop="identityname" label="职位">
                    </el-table-column>
                    <el-table-column prop="rolename" label="权限">
                    </el-table-column>
                    <el-table-column prop="remark" label="备注">
                    </el-table-column>
                    <el-table-column label="操作">
                        <template slot-scope="scope">
                            <el-button :disabled="!permissionInfo.update" type="text" size="mini"
                                @click="operData(2, scope.row)">编 辑</el-button>
                            <el-button :disabled="!permissionInfo.delete" class="ml10" type="text" size="mini"
                                @click="delOper(3, scope.row.id)">
                                删 除
                            </el-button>
                            <!-- <el-tag size="small" type="danger">成功</el-tag> -->
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <div class="bottompage-pagination mt10 flex flex-between flex--start">
                <div>
                    <el-button :disabled="!permissionInfo.add" size="small" @click="operData(1)" type="primary">新
                        增</el-button>
                    <el-button :disabled="!permissionInfo.delete" size="small" @click="delOper(1)"
                        type="danger">批量删除</el-button>
                    <el-button :disabled="!permissionInfo.delete" size="small" @click="delOper(2)" type="danger">清
                        空</el-button>

                    <el-button :disabled="!permissionInfo.upload" class="ml30" size="small" @click="printLoad(1)"
                        type="primary">下载模板</el-button>
                    <el-button :disabled="!permissionInfo.upload" size="small" @click="printLoad(2)"
                        type="primary">导入用户</el-button>
                </div>
                <div>
                    <el-pagination @size-change="pageSizeChange" @current-change="pageCurrentChange"
                        :current-page="pageInfo.pageSize" :page-sizes="[10, 50, 100, 200, 300, 400, 500]"
                        :page-size="pageInfo.pageNum" layout="total, sizes, prev, pager, next, jumper"
                        :total="pageInfo.total">
                    </el-pagination>
                </div>

            </div>

        </div>

        <el-dialog style="margin-top:-13vh" :close-on-click-modal="false" :title="title" :before-close="handleClose"
            :visible.sync="dialogVisible" width="40%">
            <div>
                <el-form ref="operForm" :rules="dialogType == 1 ? rules : {}" :model="operForm" label-width="80px">
                    <el-form-item prop="name" label="用户名称">
                        <el-input v-model="operForm.name" placeholder="用户名称"></el-input>
                    </el-form-item>
                    <el-form-item prop="code" label="用户编号">
                        <el-input :disabled="dialogType == 2" v-model="operForm.code" placeholder="用户编号"></el-input>
                    </el-form-item>
                    <el-form-item prop="phone" label="手机号">
                        <el-input v-model="operForm.phone" placeholder="手机号"></el-input>
                    </el-form-item>
                    <el-form-item prop="pwd" label="登录密码">
                        <el-input show-password type="password" v-model="operForm.pwd" placeholder="密码"></el-input>
                    </el-form-item>
                    <el-form-item prop="pwdcheck" label="确认密码">
                        <el-input show-password type="password" v-model="operForm.pwdcheck" placeholder="确认密码"></el-input>
                    </el-form-item>
                    <el-form-item prop="identityid" label="职位">
                        <el-select v-model="operForm.identityid">
                            <el-option :value="1" label="管理员"></el-option>
                            <el-option :value="2" label="操作员"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item prop="roleid" label="权限">
                        <el-select v-model="operForm.roleid" filterable placeholder="请选择">
                            <el-option v-for="item in roleList" :key="item.id" :label="item.name" :value="item.id">
                            </el-option>
                        </el-select>
                    </el-form-item>

                    <el-form-item label="备注">
                        <el-input v-model="operForm.remark" placeholder="备注"></el-input>
                    </el-form-item>

                    <el-form-item label="头像">
                        <uploadImg ref="headerImg"></uploadImg>
                    </el-form-item>
                </el-form>
            </div>

            <span slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm()">确 定</el-button>
                <el-button @click="dialogVisible = false">取 消</el-button>
            </span>
        </el-dialog>

        <xlsx :dataChange="dataChange" @parse="xlsxParse" @close="xlsxClose" @submit="xlsxSubmit"
            :dialogVisible="userXlsxVisible"></xlsx>
        <uploadParse :keys="dataKeys" :dataChange="dataChange" :dataAray="xlsxData" @close="xlsxParseClose"
            @submit="xlsxParseSubmit" :dialogVisible="xlsxDataVisible">
        </uploadParse>
    </div>
</template>

<script>
import { writeFun_array } from '@/utils/xlsx'
import { getUser, addUpdateUser, delUser, getRoleAll, fileUpload } from '@/http/api/index'
import md5 from 'md5';
import xlsx from '@/components/xlsx/index.vue';
import uploadParse from '@/components/xlsx/uploadParse.vue';
import uploadImg from '@/components/upload/img.vue'

const pageDefault = {
    pageSize: 1,
    pageNum: 10,
    total: 0
}
export default {
    data() {
        return {
            permissionInfo: {
                add: false,
                upload: false,
                select: false,
                update: false,
                delete: false,
            },

            serachForm: {},
            operForm: {},

            userXlsxVisible: false,

            isShowRole: false,
            roleList: [],

            loading: false,
            dialogVisible: false,
            dialogType: 1,
            title: "",

            xlsxData: [],
            xlsxDataVisible: false,

            dataChange: {
                "名称": "name",
                "编号": "code",
                "手机号": "phone",
                "职位": "identityid",
                "备注": "remark"
            },
            dataKeys: "code",

            rules: {
                name: [
                    { required: true, message: '请输入用户名称', trigger: 'blur' },
                    { min: 1, max: 16, message: '长度在 1 到 16 个字符', trigger: 'blur' }
                ],
                code: [
                    { required: true, message: '请输入用户编号', trigger: 'blur' },
                    { min: 1, max: 16, message: '长度在 1 到 16 个字符', trigger: 'blur' }
                ],
                phone: [
                    { required: true, message: "手机号格式异常", trigger: "blur" },
                    {
                        validator: (rule, value, callback) => {
                            if (!(/1\d{10}/.test(value))) {
                                callback(new Error("手机号格式异常"));
                            } else {
                                callback();
                            }
                        },
                        trigger: "blur",
                    },
                ],
                identityid: [
                    { required: true, message: '请输入用户职位', trigger: 'blur' },
                ],
                pwd: [
                    { required: true, message: '请输入用户密码', trigger: 'blur' },
                    // { min: 8, max: 16, message: '长度在 8 到 16 个字符', trigger: 'blur' }
                    {
                        validator: (rule, value, callback) => {
                            let check_difficult = this.$store.getters.baseInfo.pwd_complex;
                            let min_size = this.$store.getters.baseInfo.min_pwd;

                            if (value.length < min_size) {
                                callback(new Error("密码长度最短 " + min_size));
                            } else {
                                // 需要包括大写字母
                                let text = ""
                                if (check_difficult.includes("0") && !/[A-Z]/.test(value)) {
                                    text += ",大写字母"
                                }
                                // 需要小写字母
                                if (check_difficult.includes("1") && !/[a-z]/.test(value)) {
                                    text += ",小写字母"
                                }
                                // 需要数字
                                if (check_difficult.includes("2") && !/[0-9]/.test(value)) {
                                    text += ",数字"
                                }
                                // 需要特俗字符
                                if (check_difficult.includes("3") && !/[\x21-\x2F\x3A-\x40\x5B-\x60\x7B-\x7E]/.test(value)) {
                                    text += ",特殊字符"
                                }

                                if (text) {
                                    callback(new Error(`缺少:${text.slice(1)}`));
                                } else {
                                    callback();
                                }
                            }
                            // if (value !== this.operForm.pwd) {
                            //     callback(new Error("两次输入的密码不一致！"));
                            // } else {
                            //     callback();
                            // }
                        },
                        trigger: "blur",
                    },
                ],
                pwdcheck: [
                    { required: true, message: "请再次输入密码", trigger: "blur" },
                    {
                        validator: (rule, value, callback) => {
                            if (value !== this.operForm.pwd) {
                                callback(new Error("两次输入的密码不一致！"));
                            } else {
                                callback();
                            }
                        },
                        trigger: "blur",
                    },
                ],

            },

            pageInfo: Object.assign(pageDefault),
            tableData: [],

            delIds: [],

        };
    },
    watch: {
        // "operForm.identityid"(nv) {
        //     if (nv == 1) {
        //         this.isShowRole = false;
        //     } else {
        //         this.isShowRole = true;
        //         this.getRole();
        //     }
        // }

    },
    components: {
        xlsx,
        uploadParse,
        uploadImg
    },
    methods: {
        permissionCheck() {
            let permissionList = this.$store.getters.roleInfo.user;
            Object.assign(this.permissionInfo, permissionList);
            return;
        },
        getData() {
            let data = Object.assign({}, this.serachForm, this.pageInfo);
            this.loading = true;
            getUser(data).then(res => {
                this.tableData = res.data;
                this.pageInfo.total = res.total;

                this.loading = false;
            }).catch(err => {
                this.loading = false;
                this.$message.error("网络有点小问题!");
            });
            return;
        },
        getRole() {
            this.loading = true;
            getRoleAll().then(res => {
                if (res.code == 200) {
                    this.roleList = res.data.concat({ id: 0, name: '-无-', rolejson: '{}' });
                    console.log(this.roleList);
                }
                this.loading = false;
            }).catch(err => {
                this.loading = false;
                this.$message.error("网络有点小问题!");
            });
            return;
        },
        // 查询
        onSerach() {
            for (let k in this.serachForm) {
                if (!k) delete this.serachForm[k];
            }
            this.getData();
            return;
        },
        onEmpty() {
            this.serachForm = {};
            return;
        },
        // 批量删除
        tableSelectionChange(vals) {
            // 获取id
            let ids = [];
            vals.forEach(item => {
                ids.push(item.id);
            });
            this.delIds = ids;
            ids = null;
            return;
        },
        // 删除
        delOper(type, id) {
            let data;
            this.loading = true;
            if (type == 1) { // 批量删除
                if (this.delIds.length > 0) {
                    data = { type: 1, data: this.delIds };
                } else {
                    this.$message.error("请先勾选对应数据");
                }
            } else if (type == 2) { // 清空
                data = { type: 2 };
            } else if (type == 3) {  // 删除单个
                data = { type: 1, data: [id] };
            }
            if (data) {
                this.$confirm(
                    `是否删除`,
                    '提示',
                    {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        closeOnClickModal: false,
                        closeOnPressEscape: false
                    }
                )
                    .then(() => {
                        delUser(data).then(res => {
                            if (res.code == 200) {
                                this.getData();
                                this.$message.success("删除成功!");

                            }
                            this.loading = false;
                            return;
                        }).catch(err => {
                            console.error(err);
                            this.loading = false;
                            this.$message.error("网络有点小问题!");
                            return;
                        });

                    })
                    .catch(() => {
                        this.loading = false;
                        return false;
                    });

            } else {
                this.loading = false;
            }
            return;
        },
        handleClose() {
            this.resetForm();
            this.dialogVisible = false;
        },
        async fileUpload() {
            let imgurl = "";
            // 获取头像数据
            let userImg = this.$refs['headerImg'].getImgStream();
            let formdata;
            if (userImg.length == 1) {
                formdata = new FormData();
                formdata.append('file', userImg[0].raw);
                let res = await fileUpload(formdata);
                if (res.code == 200) {
                    imgurl = res.filePath;
                }
            }
            return imgurl;
        },
        getRoleName(arr) {
            let roleid = arr.roleid;
            let name = "";
            for (let v of this.roleList) {
                if (v.id == roleid) {
                    name = v.name;
                    break;
                }
            }
            return { ...arr, ...{ rolename: name } };
        },
        // 点击确认提交 - 新增和修改
        submitForm(formName = 'operForm') {
            this.$refs[formName].validate(async (valid) => {
                if (valid) {
                    try {
                        this.loading = true;
                        let userimg = await this.fileUpload();
                        let param = Object.assign({}, this.operForm, { userimg })
                        if (param.pwd == param.pwdcheck) {
                            delete param.pwdcheck;
                        } else {
                            this.$message.warning("两次密码不一致");
                            throw new Error();
                            return;
                        }
                        if (param.roleid > 0) {
                            param = this.getRoleName(param);
                        }
                        if (param.id > 0) {
                            // 检测密码是否符合要求
                            if (param.pwd) {
                                let flag = this.checkPassword(param.pwd);
                                if (!flag) {
                                    throw new Error();
                                    return;
                                }
                                param.pwd = md5(param.pwd);
                            }
                        }
                        else {
                            if (param.pwd.length != 32) {
                                param.pwd = md5(param.pwd)
                            }
                            param = [param];
                        }
                        addUpdateUser(param).then(res => {
                            if (res.code == 200) {
                                this.$message.success("操作成功");
                                this.dialogVisible = false;
                                this.getData();
                            }
                            this.loading = false;
                        }).catch(err => {
                            this.loading = false;
                            console.error(err);
                        })
                    } catch (err) {
                        this.loading = false;
                    }

                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        // 刷新 rules
        resetForm(formName = 'operForm') {
            this.$refs[formName].resetFields();
        },
        // 验证密码是否符合配置的要求
        checkPassword(value) {
            let check_difficult = this.$store.getters.baseInfo.pwd_complex;
            let min_size = this.$store.getters.baseInfo.min_pwd;

            if (value.length < min_size) {
                this.$message.error("密码长度最短 " + min_size);
                return;
            } else {
                // 需要包括大写字母
                let text = ""
                if (check_difficult.includes("0") && !/[A-Z]/.test(value)) {
                    text += ",大写字母"
                }
                // 需要小写字母
                if (check_difficult.includes("1") && !/[a-z]/.test(value)) {
                    text += ",小写字母"
                }
                // 需要数字
                if (check_difficult.includes("2") && !/[0-9]/.test(value)) {
                    text += ",数字"
                }
                // 需要特俗字符
                if (check_difficult.includes("3") && !/[\x21-\x2F\x3A-\x40\x5B-\x60\x7B-\x7E]/.test(value)) {
                    text += ",特殊字符"
                }

                if (text) {
                    this.$message.error(`缺少:${text.slice(1)}`);
                    return false;
                } else {
                    return true;
                }
            }
        },
        // type 1：add  其他：update
        operData(type, data) {
            if (type == 1) {
                this.title = "新增";
                this.dialogType = 1;

                this.operForm = {};
            } else {
                this.title = "编辑";
                this.dialogType = 2;
                delete data.pwd;
                delete data.pwdcheck;
                data.identityid = Number(data.identityid);
                this.operForm = { ...data };
            }
            this.dialogVisible = true;

        },
        // 选显示条数
        pageSizeChange(val) {
            this.pageInfo.pageNum = val;
            this.getData();
            return;
        },
        // 选页
        pageCurrentChange(val) {
            this.pageInfo.pageSize = val;
            this.getData();
            return;
        },

        // 下载模板 / 导入人员信息
        printLoad(type) {
            // 下载模板
            if (type == 1) {
                let __data = [
                    {
                        name: '小明',
                        code: 'AZ001',
                        identityid: '管理员/操作员',
                        phone: '18779564590',
                        remark: ''
                    }
                ],
                    __title = { title: '导入用户模板', rowSpan: 0 },
                    __changeData = {
                        name: '名称',
                        code: '编号',
                        identityid: '职位',
                        phone: '手机号',
                        remark: '备注'
                    },
                    __rowHeight = 15;

                writeFun_array(
                    __data,
                    __title,
                    __changeData,
                    "",
                    "",
                    "",
                    "",
                    __rowHeight,
                    "",
                    "",
                    ""
                );
            }
            // 导入人员信息
            else {
                this.userXlsxVisible = true;
            }
            return;
        },

        xlsxClose() {
            this.userXlsxVisible = false;
        },
        // 导入的数据
        xlsxSubmit(data) {

        },
        // 解析导入的数据
        xlsxParse(data) {
            let arr = data;
            if (arr.length > 0) {
                this.xlsxData = arr;
                this.xlsxDataVisible = true;

            } else {
                this.$message.error("数据为空!");
            }
            return;
        },

        xlsxParseClose() {
            this.xlsxDataVisible = false;
        },
        // 批量提交 导入人员
        xlsxParseSubmit(data) {
            this.xlsxDataVisible = false;
            data.forEach(item => {
                if (item.identityid.includes("管理")) {
                    item.identityid = 1;
                } else {
                    item.identityid = 2;
                }
            });
            addUpdateUser(data).then(res => {
                if (res.code == 200) {
                    this.$message.success("操作成功");
                    this.userXlsxVisible = false;
                    this.getData();
                } else {
                    this.$message.error("操作失败");
                }

            }).catch(err => {
                console.error(err);
            })

        }
    },
    mounted() {
        this.permissionCheck();
        if (this.permissionInfo.select) {
            this.getRole();
            this.getData();
        }
    }
}
</script>

 